package robotCross;

import abbot.finder.BasicFinder;
import abbot.finder.ComponentFinder;
import abbot.finder.ComponentSearchException;
import abbot.finder.Matcher;
import abbot.finder.matchers.ClassMatcher;
import abbot.i18n.Strings;
import abbot.tester.ActionFailedException;
import abbot.tester.JFileChooserTester;
import abbot.tester.JTextComponentTester;

import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.io.File;

/**
 * Created by hanyz on 2016/9/13.
 */
public class CrossJFileChooserTester extends JFileChooserTester {
	private ComponentFinder finder = BasicFinder.getDefault();
	private JTextComponentTester tester = new CrossJTextComponentTester();

	private Component find(Container chooser, Matcher m) {
		try {
			return finder.find(chooser, m);
		} catch (ComponentSearchException e) {
			return null;
		}
	}

	/**
	 * Sets the selected files.
	 */
	public void actionSetSelectedFiles(Component c, final File[] files) {
		final JFileChooser chooser = (JFileChooser) c;
		int mode = chooser.getFileSelectionMode();
		if (mode == JFileChooser.DIRECTORIES_ONLY) {
			String msg = Strings.get("tester.JFileChooser.dirs_only");
			throw new ActionFailedException(msg);
		}
		for (File file : files) {
			if (file.isDirectory()) {
				String msg = Strings.get("tester.JFileChooser.files_only");
				throw new ActionFailedException(msg);
			}
		}
		invokeAndWait(new Runnable() {
			public void run() {
				chooser.setSelectedFiles(files);
			}
		});
	}

	@Override
	public void actionSetFilename(Component c, String filename) {
		JTextField tf = (JTextField)
				find((JFileChooser) c, new ClassMatcher(JTextField.class));
		if (tf == null) {
			String msg = Strings.get("tester.JFileChooser.filename_not_found");
			throw new ActionFailedException(msg);
		}
		tester.actionEnterText(tf, filename);
	}
}
